let unionInfoDao = require('../dao/UnionInfoDao');
let userDao = require('../dao/userDao')
let mysqlPool = require('../dao/MySQLPool');
let tokenService = require('../service/TokenService')
let clubInfoDao = require('../dao/ClubInfoDao');
let userService = require('../service/userService');
let cconst = require('../const')

const {BusiError} = require('../exception/exception');

class UnionService{
    constructor() {

    }
    async updateUnionRoyaltySetting(uid, unionId, data){
        let user = {uid : uid};
        let result = await userDao.getUserByCondition(user);
        if(!result && result.length === 0){
            throw  new BusiError(500, "用户不存在");
        }
        let unioninfo = await unionInfoDao.getUnionInfo(unionId);
        if(!unioninfo){
            throw new BusiError(500, "大联盟不存在");
        }
        if(unioninfo.ownerUid !== uid){
            throw new BusiError(500, "用户无权限");
        }
        await  unionInfoDao.updateUnionRoyaltySetting(unionId, data);
    }

    async getUnionInfo(uid, unionId){
        let user = {uid : uid};
        let result = await userDao.getUserByCondition(user);
        if(!result && result.length === 0){
            throw  new BusiError(500, "用户不存在");
        }
        user = result[0];
        let unioninfo = await unionInfoDao.getUnionInfo(unionId);
        if(!unioninfo){
            throw new BusiError(500, "大联盟不存在");
        }
        return unioninfo;
    }

    /*async saveUnionRoyaltyRecord(recordList){
        if(recordList.length === 0){
            console.logw("saveUnionRoyaltyRecord recordList.length === 0")
            return;
        }
        //先筛选出大赢家
        let memberList = [];
        memberList.push(recordList[0]);
        for(let i = 1 ; i< recordList.length; i++){
            let r = recordList[i];
            if(r.winScore > memberList[0].winScore){
                memberList = [];
                memberList.push(r);
            }else if(r.winScore === memberList[0].winScore){
                memberList.push(r);
            }
        }
        //对大赢家进行抽水
        let unionId = memberList[0].unionID;
        let unionInfo = await unionInfoDao.getUnionInfo(unionId);
        let gameType = memberList[0].gameType;
        let royaltyRate = 10;
        if(unionInfo.royaltySetting){
            let royaltySetting = JSON.parse(unionInfo.royaltySetting);
            if(royaltySetting[gameType] !== undefined){
                royaltyRate = royaltySetting[gameType];
            }
        }
        let totalAmount = memberList[0].winScore;
        if(totalAmount <= 0){
            console.logw("saveUnionRoyaltyRecord totalAmount <= 0")
            return;
        }
        let royaltyAmount = parseInt(totalAmount*royaltyRate/100);
        for(let i =0 ; i< memberList.length; i++){
            let loyaltyRecord = {
                unionId: unionId,
                memberUid: memberList[i].uid,
                totalAmount: totalAmount,
                royaltyRate: royaltyRate,
                royaltyAmount: royaltyAmount,
                roomId: memberList[i].roomID,
                gameType: gameType
            };
            console.logw("玩家抽水数据写入数据库",loyaltyRecord)
            await unionInfoDao.saveUnionRoyaltyRecord(loyaltyRecord);
        }
    }*/

    async saveUnionRoyaltyRecord(recordList){

        //获取需要进行抽水的玩家列表
        let memberList = this.getWinnerList2(recordList);
        if(memberList.length === 0){
            console.logw("saveUnionRoyaltyRecord 赢家数量为0")
            return;
        }

        //获取联盟的抽水比例
        let unionId = memberList[0].unionID;
        let unionInfo = await unionInfoDao.getUnionInfo(unionId);
        let gameType = memberList[0].gameType;

        let gameTypeChild = memberList[0].gameTypeChild;
        if (gameTypeChild && gameTypeChild != ""){
            gameType = gameTypeChild;
        }

        let royaltyRate = cconst.sys_default_royalty_rate;
        if(unionInfo.royaltySetting){
            let royaltySetting = JSON.parse(unionInfo.royaltySetting);
            if(royaltySetting[gameType] !== undefined){
                royaltyRate = royaltySetting[gameType];
            }
        }
        let createTime = new Date();

        //对大赢家进行抽水
        for(let i =0 ; i< memberList.length; i++){
            //获取俱乐部的抽水
            let clubId = memberList[i].clubID;
            let clubInfo = await clubInfoDao.getByClubID(clubId);
            let clubRoyaltyRate = cconst.sys_default_royalty_rate;
            if(clubInfo.royaltySetting){
                let clubRoyaltySetting = JSON.parse(clubInfo.royaltySetting);
                if(clubRoyaltySetting[gameType] !== undefined && clubRoyaltySetting[gameType][memberList[i].sort] !== undefined){
                    clubRoyaltyRate = clubRoyaltySetting[gameType][memberList[i].sort];
                }
            }
            let totalAmount = memberList[i].winScore;
            if(totalAmount <= 0){
                console.logw("saveUnionRoyaltyRecord totalAmount <= 0")
                return;
            }
            let clubRoyaltyAmount = parseInt(totalAmount*clubRoyaltyRate/100);
            let royaltyAmount = parseInt(clubRoyaltyAmount*royaltyRate/100);
            let loyaltyRecord = {
                unionId: unionId,
                memberUid: memberList[i].uid,
                totalAmount: totalAmount,
                royaltyRate: royaltyRate,
                royaltyAmount: royaltyAmount,
                roomId: memberList[i].roomID,
                gameType: gameType,
                clubId:clubId,
                clubRoyaltyRate:clubRoyaltyRate,
                clubRoyaltyAmount:clubRoyaltyAmount,
                gameSort: memberList[i].sort,
                createTime: createTime
            };
            console.logw("玩家抽水数据写入数据库",loyaltyRecord)
            await unionInfoDao.saveUnionRoyaltyRecord(loyaltyRecord);
            console.log("大联盟抽水扣钱",clubRoyaltyAmount);
            await userService.updateCoins(clubId, 55, memberList[i].uid, gameType, -clubRoyaltyAmount, memberList[i].roomID, "");
            //给群主加奖卷
            await userDao.updateJiangJuanClubState(clubId,clubRoyaltyAmount);
        }
    }


    keysort(key,sortType){
        return function(a,b){
            return sortType ? ~~(a[key] < b[key]) : ~~(a[key] > b[key]);
        }
    }
    getWinnerList2(recordList){
        //先筛选出比赛前3名分数
        let memberList = [];
        let curscore = 0;
        let level = 0;
        recordList.sort(this.keysort('winScore',true));
        // console.log(recordList);
        // console.log("----------------------------------------------------");
        for(let i = 0 ; i< recordList.length; i++){
            let r = recordList[i];
            if(r.winScore <= 0 ){
                break;
            }

            if (curscore!==r.winScore){
                curscore = r.winScore;
                level=level+1;
                if (level>3){
                    break;
                }
                r.sort=level;
                memberList.push(r);
            }else{
                r.sort=level;
                memberList.push(r);
            }

        }
        return memberList;
    }

    //获取需要进行抽水的玩家列表
    getWinnerList(recordList){
        //先筛选出比赛前3名分数
        let memberList = [];
        let record1 = null;
        let record2 = null ,record3 = null;
        let records =  [];
        for(let i = 0 ; i< recordList.length; i++){
            let r = recordList[i];
            if(r.winScore <= 0 ){
                continue;
            }
            if(!record1 || r.winScore > record1.winScore){
                if(record1){
                    if(record2){
                        record3 = record2;
                        records["3"] = record3;
                    }
                    record2 = record1;
                    records["2"] = record2;
                }
                record1 = r;
                records["1"] = record1;
            }else if(!record2 || r.winScore > record2.winScore){
                if(r.winScore === record1.winScore){
                    continue;
                }
                if(record2){
                    record3 = record2;
                    records["3"] = record3;
                }
                record2 = r;
                records["2"] = record2;
            }else if(!record3 || r.winScore > record3.winScore){
                if(r.winScore === record2.winScore){
                    continue;
                }
                record3 = r;
                records["3"] = record3;
            }
        }
        console.log("saveUnionRoyalty + 前3名分数", records);
        for(let i in recordList){
            let r = recordList[i];
            if(r.winScore <= 0 ){
                continue;
            }
            for(let j in records) {

                if(r.winScore === records[j].winScore){
                    r.sort = j;
                    memberList.push(r);
                    break;
                }
            }
        }
        return memberList;
    }



    /*async getUnionRoyaltyRecordList(date, unionId){
        let startTime = new Date(date);
        let endTime = new Date(startTime.getTime() + 24 * 60 * 60 *1000);
        return await unionInfoDao.getUnionRoyaltyRecordList(unionId, startTime, endTime);
    }*/

    async getUnionRoyaltyRecordList(date, unionId, clubId){
        /*let startTime = new Date(date);
        let endTime = new Date(startTime.getTime() + 24 * 60 * 60 *1000);*/

        let unionRecordList = [];
        if(clubId && clubId !== undefined){
            let clubRecordList = await this.getUnionClubRoyaltyRecordList(date, unionId, clubId);
            unionRecordList.push(clubRecordList);
            return unionRecordList;
        }
        let clubIds = await  unionInfoDao.getUnionClubIdList(unionId);
        for(let i in clubIds){
            let clubId = clubIds[i].clubId;
            let clubRecordList = await this.getUnionClubRoyaltyRecordList(date, unionId, clubId);
            unionRecordList.push(clubRecordList);
        }
        return unionRecordList;
    }

    async getUnionClubRoyaltyRecordList(date, unionId, clubId){
        let startTime = new Date(date);
        let endTime = new Date(startTime.getTime() + 24 * 60 * 60 *1000);
        let clubRoyaltyRecordList = await unionInfoDao.getUnionClubRoyaltyRecordList(unionId, clubId, startTime, endTime);
        let clubTotalAmount = 0;
        for(let i in clubRoyaltyRecordList){
            let roomInfo = clubRoyaltyRecordList[i].roomInfo;
            clubTotalAmount = clubTotalAmount + roomInfo.roomTotalAmount;
        }
        let clubInfo = await clubInfoDao.getByClubID(clubId);
        clubInfo.clubTotalAmount = clubTotalAmount;
        return {"clubRoyaltyRecordList": clubRoyaltyRecordList, "clubInfo": clubInfo};
    }

}



let unionService = new UnionService();
module.exports = unionService;